<template>
	<view class="group-chat">
		<uni-nav-bar dark :left-width="0" :fixed="true" :right-width="100" :right-image="userInfo.userType==2?'2':''" title="消息" title-align="left" background-color="#fff" title-size="23px" :border="false" :show-module="showModule" :grade-id="userInfo.stratum==2?userInfo.gradeId[0]:-1" color="#262E3F" @clickLeft="search()" @clickRight="showAddModule()" />
		<view class="list" v-if="friend_list.length>0">
			<view class="cl-item" @longpress="delChatSession(item)" @click="chatDetail(item)" v-for="(item, i) in friend_list" :key="i">
				<view class="head-portrait">
					<image :src="headHandle(item)" mode="aspectFill"></image>
					
				</view>
				<view class="time-info">
					<view class="name-cont" v-if="item.gradeId&&item.notice">
						<view class="time-name">
							<view>
								<text class="name">{{gradeMap[item.gradeId]}}</text>
								<text class="tag tag-official">官方</text>
							</view>
							<text class="time">{{utils.handleTs(new Date(item.addTime.split('-').join('/')).getTime())}}</text>
						</view>
						<view class="content-num">
							<text class="cont">{{item.notice}}</text>
							<text class="num" v-if="item.unCheckNum>0">{{item.unCheckNum>99?'99+':item.unCheckNum}}</text>
						</view>
						
					</view>
					<view class="name-cont" v-else>
						<view class="time-name">
							<view>
								<text class="name">{{item.name}}</text>
								<text class="tag" v-if="!item.userType">群聊</text>
							</view>
							<text class="time" v-if="item.msgNew">{{utils.handleTs(item.msgNew.createTime)}}</text>
						</view>
						<view class="content-num">
							<text class="cont" v-html="utils.emojiName(item.msgNew, userId)"></text>
							<text class="num" v-if="item.msgCount>0">{{item.msgCount>99?'99+':item.msgCount}}</text>
						</view>
						
					</view>
				</view>				
			</view>
		</view>
		<view v-if="friend_list.length==0" class="no-msg-list">
			暂无联系人
		</view>
	</view>
</template>

<script>
	import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue'

	export default {
    	components: {
			uniNavBar
		},
		data(){
			return {
				userInfo: {},
				gradeMap: {},
				newPrivateGroupMsg: null,
				userId: '',

				friend_list: [],
				showModule: false
			}
		},
		onShow(){
			this.newPrivateGroupMsg = uni.getStorageSync('newMsgHis') || {}
			// 去往聊天页面之后，未读消息提示去掉
			if(this.friend_list.length>0){
				friendsMsgHandle(this, this.friend_list)
			}
			this.getfindChatSession()
			this.getUserVersion()
		},
		onLoad(){
			uni.removeStorageSync('xd_tribute_info')
			this.userInfo = getApp().globalData.userInfo;
			uni.$on('privateChat', this.getMsg);
			uni.$on('newMsgHis', this.getNewHis)
		},
		onUnload(){
			uni.$off('privateChat', this.getMsg);
			uni.$off('newMsgHis', this.getNewHis)
		},
		methods: {
			search(){

			},
			showAddModule(){
				this.showModule = !this.showModule
			},
			headHandle(info){
				// 处理头像显示
				let str = ''
				let sex = info.sex>0 ?info.sex : 1

				str = info.userType&&info.avatarUrl?this.api.xiaodeObsUrl+info.avatarUrl:''

				if(!str){
					str = info.userType?`/static/${info.userType==1?`stu${sex}`:'te1'}.png`:info.type==1?'/static/u16.png':info.type==5?'/static/txl/qlx.png':info.notice?'/static/notice.png':'/static/txl/qlx2.png'
				}
				return str;
			},
			delChatSession(item){
				if(!item.userType) return
				this.utils.showModal('', '确认删除消息？', del)

				let that = this
				function del(){
					that.api.post('chatGroupManage/delChatSession', {
						id: item.id,
						type: item.userType
					}).then(res=>{
						if(res.data.state!='ok')return;
						let delI = that.friend_list.findIndex(info=>info.id==item.id && info.userType==item.userType)
						that.friend_list.splice(delI, 1)
					})
				}
			},
			getGradeNotice(){
				this.api.get('chatGroupManage/findGradeNotice', {
					gradeIds: JSON.stringify([2]),
					page: 1,
					limit: 1
				}).then(res=>{
					if(res.data.state != 'ok') return;
					this.gradeMap = getApp().globalData.baseInfo.gradeMap;
					let unCheckNum = res.data.unCheckNum
					let data = res.data.notice;
					for (const key in data) {
						if (data[key].list.length>0) {
							data[key].list[0].gradeId = key
							data[key].list[0].unCheckNum = unCheckNum[key]
							this.friend_list.push(data[key].list[0])
							
						}
					}
					friendsMsgHandle(this, this.friend_list)
				})
			},
			getfindChatSession(){
				
				// this.friend_list = uni.getStorageSync('xiaode_friend_list')
				// if(this.friend_list.length>0){
				// 	friendsMsgHandle(this, this.friend_list)
				// 	this.gradeMap = {1: '高一', 2: '高二', 3: '高三'}
				// 	return
				// }
				this.api.get('chatGroupManage/findChatSession').then(res=>{
					if(res.data.state !='ok')return
					let userInfo = getApp().globalData.userInfo;
					
					this.userId = userInfo.accountId;
					this.userInfo = userInfo
					this.friend_list = res.data.friends.concat(res.data.schoolChatGroup, res.data.familyChatGroup, res.data.commonChatGroup, res.data.exampleGroup);
					
					this.getGradeNotice()
				})
			},

			getUserVersion(){
				this.api.get('chatGroupManage/checkUserVersion', {
					version: 0
				}).then(res=>{
					if(res.data.state!='ok')return;
					if(res.data.needUpdate){

					}
				})
			},
			getMsg(data){
				let o = data.msg || {}, msg = []
				msg = o.chatTyp==2?o.privateMsgList:o.groupMsgList;
				this.newPrivateGroupMsg = uni.getStorageSync('newMsgHis') || {}

				if(o.returnEventType==1&&msg.length>0){
					let data = msg[0]
					let friendList = uni.getStorageSync('xiaode_friend_list'), id = -1;
					id = data.from || data.fromId
					if(friendList.findIndex(item=>item.accountId == id) == -1) {
						this.getfindChatSession()
					}else{
						friendsMsgHandle(this, this.friend_list)
					}
				}	
			},
			getNewHis(e){
				this.newPrivateGroupMsg = e;
				if(this.userId){

					friendsMsgHandle(this, this.friend_list)

				}
			},

			chatDetail(item){
				if(!item.userType && item.type){
					this.msgList(item)
					return
				}
				if(item.logId){
					uni.navigateTo({
						url: '/pages/message/notice-list'
					})
					return
				}
				if(!item.userType) return
				let url = item.avatarUrl||'';
				uni.navigateTo({
					url: `/pages/student/chat-page?toUserType=${item.userType}&id=${item.id}&accountId=${item.accountId}&name=${item.name}&avatarUrl=${url}`
				})
			},
			msgList(item){
				let userType = getApp().globalData.userInfo.userType
				uni.navigateTo({
					url: `/pages/group/group-msg?examId=${item.id}&type=${this.userInfo.userType}&tabBar=1`
				})
			}
		}
	}
	function friendsMsgHandle(that, list){
		that.friend_list = []
		let count = 0;
		for(let i=0; i<list.length; i++){
			let info = list[i];
			if(!info.logId){
				let toUserId = info.accountId
				let wsid = `${toUserId}${that.userId}`
				if(!info.userType){ // 群聊
					wsid = `${that.userId}${info.id}`
				}
				if(that.newPrivateGroupMsg[wsid]){
					let newMsg = that.newPrivateGroupMsg[wsid], lastNewMsg = newMsg.data||[]
					info.msgNew = lastNewMsg[lastNewMsg.length-1]
					info.msgCount = newMsg.count
					if(count==0){
						count = newMsg.count
					}
				}
			}
			
		}
		function func(a, b){
			let obj1 = a.msgNew || (a.addTime&&a.logId?{createTime: new Date(a.addTime.split('-').join('/')).getTime(), notice: 111} : {createTime: -1, content: ''}), 

			obj2 = b.msgNew || (b.addTime&&b.logId?{createTime: new Date(b.addTime.split('-').join('/')).getTime()}:{createTime: -1, content: ''})

			return obj2.createTime-obj1.createTime;
		}
		list.sort(func);
		that.friend_list = list;
		uni.setStorageSync('xiaode_friend_list', that.friend_list)
		if (count>0) {
			// uni.showTabBarRedDot({index: 3})
		}else{
			// uni.hideTabBarRedDot({index: 3})
		}
		// that.utils.showRedDot()
		if(count==0){
			// for (const key in that.newPrivateGroupMsg) {
			// 	if (key.indexOf(that.userId)>0&&that.newPrivateGroupMsg[key].count>0) {
			// 		delete that.newPrivateGroupMsg[key]
					
			// 	}
			// }
			uni.setStorageSync('newMsgHis', that.newPrivateGroupMsg)
		}
	}
</script>
<style lang="less">
	.group-chat{
		overflow: hidden;
		.flex{
			display: flex;
			align-items: center;
		}
		.head{
			width: 60rpx;
			height: 60rpx;
		}
		.you{
			width: 28rpx;
			height: 28rpx;
		}
		.list{
			padding-top: 24rpx;
			position: relative;
			&::after{
				position: absolute;
				content: '';
				width: 200%;
				left: 0;
				height: 2rpx;
				top: 0;
				background: #EEEEEE;
				transform: scale(0.5) translateX(-50%);
			}
		}
		.title{
			padding: 0 32rpx;
			height: 58rpx;
			line-height: 58rpx;
			font-size: 24rpx;
			color: #7f7f7f;
			background: #f2f2f2;
		}
		.cl-item{
			display: flex;
			align-items: center;
			height: 160rpx;		
			.time{
				font-size: 24rpx;
				color: #BCBCBC;
				white-space: nowrap;
			}
		}
		.head-portrait {
			position: relative;
			margin: 0 32rpx;
			font-size: 0;
			image{
				border-radius: 44rpx;
				width: 88rpx;
				height: 88rpx;
			}
			
		}
		.name-cont{
			height: 160rpx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			width: 100%;
			
			font-size: 28rpx;
			box-sizing: border-box;
		}
		.time-info{
			display: flex;
			align-items: center;
			justify-content: space-between;
			width:  calc(100% - 184rpx);
			position: relative;
			&::after{
				position: absolute;
				content: '';
				width: 200%;
				left: 0;
				height: 2rpx;
				bottom: 0;
				background: #EEEEEE;
				transform: scale(0.5) translateX(-50%);
			}
		}
		.time-name{
			display: flex;
			justify-content: space-between;
			align-items: center;
			.tag{
				margin-left: 10rpx;
				border-radius: 4rpx;
				padding: 0 4rpx;
				line-height: 30rpx;
				font-size: 24rpx;
				color: #28C2CD;
				background: #D4F3EE;
			}
			.tag-official{
				color: #FA7F45;
				background: #FEE8DD;
			}
		}
		.content-num{
			margin-top: 10rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			.num{
				display: inline-block;
				padding: 0 8rpx;
				height: 40rpx;
				line-height: 40rpx;
				min-width: 40rpx;
				text-align: center;
				box-sizing: border-box;
				border-radius: 20rpx;
				background: #FA7F45;
				color: #fff;
				font-size: 24rpx;
				z-index: 8;
			}
			
			.cont{
				width: 86%;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
				height: 32rpx;
				line-height: 32rpx;
				// display: -webkit-box;
				// -webkit-line-clamp: 1;
				// -webkit-box-orient: vertical;
				font-size: 24rpx;
				color: #999;
			}
		}


		.scholl-group{
			.cl-item{
				
				height: 140rpx;
			}
			.time-info{
				border: none;
			}
		}
		.no-teacher{
			margin: 20rpx 0 ;
			text-align: center;
			font-size: 24rpx;
		}
	}
	.no-msg-list{
		padding-top: 40rpx;
		text-align: center;
	}
</style>